<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<div><el-button type="warning" class="item-gap" size="small" :loading="exportLoading" @click="onExportExcel">导出</el-button></div>
				</div>
				<div class="flex-end-center-wrap">
					<currentTime :current-time="currentTime"></currentTime>
					<jk-select v-model="searchParams.processCode" value-key-name="code" :option-list="processList" placeholder="工序" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
					<jk-search-button class="" @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>
		<jk-card>
			<jk-table
				border
				:data="tableData"
				show-footer
				:footer-method="footerMethod"
				:height="tableHeight + 20"
				:loading="tableLoading"
			>
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
				</vxe-column>
			</jk-table>
			<!-- 分页组件 -->
			<!-- <footer ref="box2" class="flex-end-center margin-top-10">
        <jk-page
          :page-index="searchParams.pageNo"
          :page-sizes="searchParams.pageSizes"
          :page-size="searchParams.pageSize"
          :total="searchParams.count"
          @on-change="onPage"
        />
      </footer> -->
		</jk-card>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { formatDate, formatTime, pageConfig } from '/src/utils/jk/jk-tool';
    import permissionMixin from '../../../mixins/permission-mixin';
    import { getInfo } from '../../../api/login';
    import listView from './components/list-view';
    import chartView from './components/chart-view';
    // import scheduleShift from '../scheduleShiftProductionReport/scheduleShift';
    import {
        reportProductionYieldMonitor
    } from '../../../api/production/reportProductionYieldMonitor';
    import { systemUserColumnConfigGet } from '@/api/system/column-config';
    import currentTime from './components/current-time';
    import XEUtils from 'xe-utils';
    export default {
        name: 'ReportProductionYieldMonitor',
        mixins: [permissionMixin, calHeight],
        components: {
            listView,
            chartView,
            currentTime
        },
        data() {
            return {
                prefix: '',
                viewType: 'listView',
                // processList: [],
                processList: [],
                tableColumnList: [],
                dataId: null,
                tableLoading: false,
                exportLoading: false,
                tableData: [],
                searchParams: {
                    count: 0,
                    // pageNo: pageConfig.pageNo,
                    // pageSize: pageConfig.pageSize,
                    machineName: null
                    // processCode: '',
                    // belongDate: '',
                    // groupId: 1
                    // workshopId: null
                },
                currentTime: '',
                interVal2: {},
                noCalKey: ['allQty'],
                interVal: {}
            };
        },
        methods: {
            getMenuColumnListRequest() {
                return systemUserColumnConfigGet({ path: 'ReportProductionYieldMonitor', filterShow: true }).then(res => {
                    if (res.data.status === 200) {
                        this.tableColumnList = res.data.res.columnConfigList && res.data.res.columnConfigList.length ? res.data.res.columnConfigList[0].itemList : [];
                    }
                });
            },
            footerMethod({ columns, data }) {
                return [
                    columns.map((column, columnIndex) => {
                        if (columnIndex === 0) {
                            // return `合计: ${this.totalData.totalOutputM || 0}M; ${this.totalData.totalOutputKg || 0}KG`;
                            return `合计`;
                        }
                        if (this.noCalKey.includes(column.property)) {
                            return XEUtils.sum(data, column.property);
                        }
                        return null;
                    })
                ];
            },
            getUserInfoRequest() {
                return getInfo().then(res => {
                    if (res.data.status === 200) {
                        this.workshopList = res.data.res.workshop.workshops;
                        this.getListRequest();
                    }
                });
            },
            runTime() {
                this.yearMonthDay = formatTime(Date.now()).slice(0, 10);
                this.hourMinuteSecond = formatTime(Date.now()).slice(-9);
                this.currentTime = formatTime(Date.now());
                clearInterval(this.interVal2);
                this.interVal2 = setInterval(() => {
                    this.currentTime = formatTime(Date.now());
                }, 1000);
            },
            runData() {
                this.getListRequest();
                clearInterval(this.interVal);
                this.interVal = setInterval(() => {
                    this.getListRequest();
                }, 10000);
            },
            clearTimer() {
                clearInterval(this.interVal);
                clearInterval(this.interVal2);
            },
            /** 查询列表 */
            getListRequest() {
                // 页面加载loading
                // this.tableLoading = true;
                reportProductionYieldMonitor(this.searchParams).then(res => {
                    // this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res;
                        this.searchParams.count = res.data.count;
                    }
                });
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                // this.searchParams.pageNo = 1;
                // this.searchParams.count = 1;
                this.getListRequest();
            },
            /** 导出按钮操作 */
            onExportExcel() {
                this.exportLoading = true;
                const params = JSON.parse(JSON.stringify(this.searchParams));
                params.pageNo = 1;
                params.pageSize = 500;
                this.$modal.confirm('是否确认导出所有数据数据项?').then(() => {
                    this.exportLoading = true;
                    return reportProductionYieldMonitor(params);
                }).then(res => {
                    if (res.data.status === 200) {
            import('@/vendor/Export2Excel').then(excel => {
              const tHeader = this.tableColumnList.map(x => x.title);
              const filterVal = this.tableColumnList.map(x => x.keyName);
              const list = res.data.res ? res.data.res : [];
              // 保留一位小数设备名称
              // const arr = ['单锭效率'];
              // const minification = ['纱疵'];
              // const arrName = ['纱疵', '纱线接头(捻接)', '自然纱线断头', '很短的粗节', '短粗节/或标准差', '长粗节', '细节', '启动期间纱支疵点数的公差上限', '启动期间纱支疵点数的公差下限', '运行期间纱支偏差的公差上限', '运行期间纱支疵点数的公差下限', 'D+ [/100km]', 'D- [/100km]', 'CD+ [/100km]', 'CD- [/100km]', '周期性瑕疵点', '深色异纤(浅色纱线中的深色纤维)', '纱线接头的公差上限', '纱线接头的公差下限', 'swNSL [/100km]', 'swT [/100km]'];
              // list.forEach((obj) => {
              //   Object.keys(obj).forEach((key) => {
              //     arr.forEach(y => {
              //       if (key === y) {
              //         obj[key] = this.getOneFloat(obj[key]);
              //       }
              //     });
              //     arrName.forEach(x => {
              //       if (key === x) {
              //         obj[key] = Math.ceil(obj[key]);
              //       }
              //     });
              //     minification.forEach(x => {
              //       if (key === x) {
              //         obj[key] = this.minification(obj[key]);
              //       }
              //     });
              //   });
              // });
              const data = this.formatJson(filterVal, list);
              excel.export_json_to_excel({
                header: tHeader,
                data,
                filename: `${this.$route.meta.title}(${formatDate(Date.now())})`,
                autoWidth: true,
                bookType: 'xlsx'
              });
            });
                    }
                    this.exportLoading = false;
                });
            },
            // Math.ceil(number);
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => {
                    return v[j];
                }));
            },
            minification(num) {
                const numMain = Number(num);
                return numMain / 100;
            },
            getOneFloat(num) {
                const numMain = Number(num);
                return parseFloat(numMain.toFixed(1));
            },
            async getDependentData() {
                // this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                this.processList = this.$store.state.user.userProcess.processList;
                if (!this.searchParams.processCode) {
                    this.$set(this.searchParams, 'processCode', this.$store.state.user.userProcess.defaultProcessCode || '');
                }
                // this.getCurrentTimeScheduleShift();
                await this.getUserInfoRequest();
                await this.getMenuColumnListRequest();
                this.getListRequest();
            }
        },
        beforeRouteEnter(to, from, next) {
            next((_this) => {
                _this.runTime();
                _this.runData();
            });
        },
        beforeRouteLeave(to, from, next) {
            this.clearTimer();
            next();
        },
        mounted() {
            this.getDependentData();
        }
    };
</script>
<style scoped>
</style>
